package com.stony.controller;

import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.stony.comm.MediaTypes;
import com.stony.model.HostModel;
import com.stony.service.HostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;


/**
 * Created by ShiHui on 2014/6/3.
 */

@Controller
@RequestMapping("/host")
public class HostController {


    Logger log = LoggerFactory.getLogger(HostController.class);

    @Resource
    public HostService hostService;

    @ResponseBody
    @RequestMapping(value = "/addHost", produces = MediaTypes.JSON, method = RequestMethod.POST)
    public Object addHost(HttpServletResponse response,
                       @RequestParam String hostTypeName,
                       @RequestParam String hostname,
                       @RequestParam int port,
                       @RequestParam String authMechanism,
                       @RequestParam String username,
                       @RequestParam String password) {
        HostModel host = new HostModel();
        host.setType(hostTypeName);
        host.setHost(hostname);
        host.setPort(port);
        host.setAuth(authMechanism);
        host.setUsername(username);
        host.setPassword(password);
        Map data = new HashMap();
        data.put("status",hostService.saveHost(host) ? "OK" : "添加Host失败！");
        return data;
    }

    /**
     *
     * @param model
     * @param id host id
     * @param request
     * @return
     */
    @RequestMapping(value = "/{id}")
    public String index(ModelMap model, @PathVariable int id, HttpServletRequest request) {
        log.debug("host get : {}", id);
        HostModel host = hostService.getHost(id);
        Map data = hostService.getDBInfos(host.getHost(), host.getPort());
        model.addAttribute("dbInfos", data);
        model.addAttribute("id", id);
        model.addAttribute("path", request.getContextPath());
        model.addAttribute("server", (host.getHost() + ":" + host.getPort()));
        model.addAttribute("datastr", JSON.toJSON(data));
        return "mongo/host";
    }

    @ResponseBody
    @RequestMapping(value = "/ping", produces = MediaTypes.JSON)
    public  Object ping(){
        Map data = new HashMap();
        data.put("status", "OK");
        return data;
    }


    @RequestMapping(value = "/table")
    public String table(ModelMap model, HttpServletRequest request) {
        model.addAttribute("path", request.getContextPath());
        //1/read/letter
        int id = 1;
        String name = "read";
        String coll = "letter";

        HostModel host = hostService.getHost(id);
        model.addAttribute("hosts", hostService.getHosts());

        Map data = hostService.getDBAllInfos(host.getHost(), host.getPort());
        model.addAttribute("collInfos", ((Map)data.get(name)).get("coll_stats"));
        model.addAttribute("dbInfos", data);
        model.addAttribute("id", id);
        model.addAttribute("path", request.getContextPath());
        model.addAttribute("name", name);
        model.addAttribute("coll", coll);
        model.addAttribute("server", (host.getHost() + ":" + host.getPort()));

        return "pages/collection";
    }


    @ResponseBody
    @RequestMapping(value = "/query", produces = MediaTypes.JSON)
    public Callable<Object> query(@RequestParam final int id,
                         @RequestParam final String name,
                         @RequestParam final String coll,
                         @RequestParam final int skip,
                         @RequestParam final int limit,
                         @RequestParam final String body){
        log.debug("id : {}, name : {}, coll : {}, skip : {}, limit : {}, body : {}", id, name, coll, skip, limit, body);

//        Map<String,List<DBObject>> data = new HashMap<String,List<DBObject>>();
//        data.put("data",list);
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                HostModel host = hostService.getHost(id);
                List<DBObject> list = null;
                if(body == null || body.isEmpty()){
                    list = hostService.findAllData(host, name, coll, skip, limit);
                }else{
                    BasicDBObject criteria = (BasicDBObject) com.mongodb.util.JSON.parse(body);
                    list = hostService.findAllData(host, name, coll, skip, limit, criteria);
                }
                return list;
            }
        };
        return callable;
    }
}
